package images_api

import (
	"fmt"
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/ctype"
	"ginBolg/models/res"
	"ginBolg/plugins/qiniu"
	"ginBolg/utils"
	"github.com/gin-gonic/gin"
	"io/fs"
	"io/ioutil"
	"os"
	"path"
	"strings"
)

var (
	// WhiteImageList 图片后缀白名单
	WhiteImageList = []string{
		"jpg", "jpeg", "png", "gif", "webp", "ico", "svg", "tiff",
	}
)

type FileUploadResponse struct {
	FileName string `json:"file_name"`
	Success  bool   `json:"success"`
	Msg      string `json:"msg"`
}

func (ImagesApi) ImageUploadView(c *gin.Context) {
	// 上传多个文件
	form, err := c.MultipartForm()
	if err != nil {
		res.Fail(err.Error(), c)
		return
	}
	files, ok := form.File["images"]
	if !ok {
		res.Fail("文件不存在", c)
	}
	basePath := global.Config.Upload.Path
	// 判断路径是否存在
	_, err = os.ReadDir(basePath)
	if err != nil {
		err := os.MkdirAll(basePath, fs.ModePerm)
		if err != nil {
			global.Log.Error(err)
		}
	}

	var resList []FileUploadResponse

	for _, file := range files {
		fileName := file.Filename
		nameList := strings.Split(fileName, ".")
		suffix := strings.ToLower(nameList[len(nameList)-1])
		if !utils.IsInList(suffix, WhiteImageList) {
			resList = append(resList, FileUploadResponse{
				FileName: file.Filename,
				Success:  false,
				Msg:      fmt.Sprintf("非法的图片格式"),
			})
			continue
		}

		filePath := path.Join(basePath, file.Filename)
		// 判断图片大小
		size := float64(file.Size) / 1024 / 1024
		if size > float64(global.Config.Upload.Size) {
			resList = append(resList, FileUploadResponse{
				FileName: file.Filename,
				Success:  false,
				Msg:      fmt.Sprintf("图片大小超过 %d MB限制", global.Config.Upload.Size),
			})
		}

		fileObj, err := file.Open()
		if err != nil {
			global.Log.Error(err)
		}
		byteData, err := ioutil.ReadAll(fileObj)
		imageHash := utils.Md5(byteData)
		// 去数据库中查寻，图片是否存在
		var bannerModel models.BannerModel
		tx := global.DB.Take(&bannerModel, "hash = ?", imageHash)
		if tx.Error == nil {
			// 找到了
			resList = append(resList, FileUploadResponse{
				FileName: file.Filename,
				Success:  true,
				Msg:      "上传成功",
			})
			continue
		}

		fileType := ctype.Local
		if global.Config.QiNiu.Enable {
			qiNiuPath, err := qiniu.UploadImage(byteData, fileName, global.Config.QiNiu.Prefix)
			if err != nil {
				resList = append(resList, FileUploadResponse{
					FileName: fileName,
					Success:  false,
					Msg:      err.Error(),
				})
				continue
			}
			filePath = qiNiuPath
			fileType = ctype.QiNiu
		} else {
			err = c.SaveUploadedFile(file, filePath)
			if err != nil {
				global.Log.Error(err)
				resList = append(resList, FileUploadResponse{
					FileName: fileName,
					Success:  false,
					Msg:      err.Error(),
				})
				continue
			}

		}
		// 图片入库
		global.DB.Create(&models.BannerModel{
			Path:      filePath,
			Hash:      imageHash,
			Name:      fileName,
			ImageType: fileType,
		})
		resList = append(resList, FileUploadResponse{
			FileName: fileName,
			Success:  true,
			Msg:      "上传成功",
		})
	}
	res.OkWithData(resList, c)
}
